<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="40%"
    :before-close="handleClose"
  >
    <div class="coupon-dialog">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="优惠券名称" prop="coupon_name">
          <el-input
            placeholder="输入优惠券名称"
            style="width: 100%"
            v-model="ruleForm.coupon_name"
          />
        </el-form-item>
        <el-form-item label="优惠券面值" prop="coupon_price">
          <el-input
            placeholder="输入优惠券面值"
            style="width: 100%"
            v-model="ruleForm.coupon_price"
          />
        </el-form-item>
        <div>
          <el-form-item
            label="优惠券描述"
            prop="coupon_remark"
            style="width: 100%"
          >
            <el-input
              placeholder="描述"
              style="width: 100%"
              type="textarea"
              :row="2"
              v-model="ruleForm.coupon_remark"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="使用条件" prop="user_limit">
            <el-radio-group v-model="ruleForm.user_limit" @change="changeLimit">
              <el-radio :label="1"
                >满减
                <el-input
                  placeholder="最低消费"
                  style="width: 50%"
                  v-model="ruleForm.use_min_price"
                />元
              </el-radio>
              <el-radio :label="0">不限</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <el-form-item label="发放数量" prop="total_count">
          <el-input
            placeholder="输入发放数量"
            style="width: 60%"
            v-model="ruleForm.total_count"
          />
          <span style="margin-left: 10px"> 0为不限 </span>
        </el-form-item>
        <!-- <el-form-item label="剩余领取数量" prop="remain_count">
          <el-input
            placeholder="输入剩余领取数量"
            style="width: 100%"
            v-model="ruleForm.remain_count"
          />
        </el-form-item> -->
        <el-form-item label="每人限领" prop="receive_limit">
          <el-input
            placeholder="每个人领取的优惠券数量"
            style="width: 100%"
            v-model="ruleForm.receive_limit"
          />
        </el-form-item>
        <!-- <div>
          <el-form-item
            label="发放目标"
            prop="receive_type"
            style="width: 100%"
          >
            <el-radio-group
              v-model="ruleForm.receive_type"
              @change="changeType"
            >
              <el-radio :label="1" style="width: 100%">所有用户</el-radio>
              <el-radio :label="2" style="width: 100%; margin: 10px 0">
                按注册时间
                <el-date-picker
                  v-model="ruleForm.reg_start_time"
                  style="width: 35%; margin: 10px 0"
                  type="datetime"
                  placeholder="注册开始时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
                <span style="margin: 0 10px">至</span>
                <el-date-picker
                  v-model="ruleForm.reg_end_time"
                  style="width: 35%"
                  type="datetime"
                  placeholder="注册结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-radio>
              <el-radio
                :label="3"
                style="height: auto; width: 100%; white-space: pre-wrap"
              >
                指定用户
                <el-input
                  placeholder="请输入手机号，多个手机号用英文逗号隔开 "
                  style="width: 70%"
                  v-model="ruleForm.userids"
                />
                直接发放给用户，无需领取
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div> -->

        <!-- <el-form-item
          label="领取日期"
          style="width: 100%"
          v-if="ruleForm.receive_type !== 3"
        >
          <el-date-picker
            v-model="ruleForm.start_time"
            style="width: 40%"
            type="datetime"
            placeholder="优惠券领取开启时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span style="margin: 0 10px">至</span>
          <el-date-picker
            v-model="ruleForm.end_time"
            style="width: 40%"
            type="datetime"
            placeholder="优惠券领取结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item> -->

        <!-- <el-form-item label="生效日期" style="width: 100%">
          <el-date-picker
            v-model="ruleForm.start_use_time"
            style="width: 40%"
            type="datetime"
            placeholder="优惠券使用开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span style="margin: 0 10px">至</span>
          <el-date-picker
            v-model="ruleForm.end_use_time"
            style="width: 40%"
            type="datetime"
            placeholder="优惠券使用结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item> -->

        <!-- <el-form-item label="排序" prop="sort">
          <el-input
            placeholder="排序"
            style="width: 100%"
            v-model="ruleForm.sort"
          />
        </el-form-item> -->

        <el-form-item label="商品类型" prop="goods_type">
          <el-radio-group v-model="ruleForm.goods_type" @change="goodsChange">
            <el-radio :label="1">全部商品可用</el-radio>
            <el-radio :label="2">
              指定商品可用
              <el-button
                v-if="ruleForm.goods_type == 2"
                size="small"
                type="primary"
                @click="openShop"
              >
                添加商品
              </el-button>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status" :span="24">
          <el-radio-group
            v-model="ruleForm.status"
            :disabled="ruleForm.id ? true : false"
          >
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="select-shop-title" v-if="ruleForm.goods_type == 2">
          <div v-if="shopTable.length > 0">已选择{{ shopTable.length }}条</div>
        </div>
        <div
          class="select-shop"
          v-if="ruleForm.goods_type == 2 && shopTable.length > 0"
        >
          <el-table border stripe :data="shopTable" :max-height="400">
            <el-table-column prop="goods_name" label="商品名称">
              <template #default="{ row }">
                <div class="manage-info">
                  <el-image
                    :preview-teleported="true"
                    style="width: 50px; min-width: 50px; height: 50px"
                    :src="imgSrc(row.cover)"
                    :zoom-rate="1.2"
                    :preview-src-list="[imgSrc(row.cover)]"
                    :initial-index="4"
                    fit="cover"
                    class="img-box"
                  />
                  <div class="right">
                    <div>
                      <label>商品名称：</label>
                      <span>{{ row.goods_name }} </span>
                    </div>
                    <div>
                      <label>商品编号：</label>
                      <span>{{ row.code }} </span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="库存" show-overflow-tooltip>
              <template #default="{ row }">
                <div>累计库存： {{ row.stock_total }}</div>
                <div>剩余库存： {{ row.stock_total - row.stock_sales }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" show-overflow-tooltip width="80">
              <template #default="scoped">
                <el-button type="danger" @click="del(scoped.$index)" link>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
  <shopPage ref="shopPageRef" @selectFun="selectFun" />
</template>
<script setup>
import {
  addApi,
  saveApi,
  coupon_goodsApi,
} from "@/plugins/api/shopping/coupon";
import shopPage from "./DialogCoupon-shop.vue";
let ruleForm = ref({});
let rules = {
  coupon_name: [
    { required: true, message: "请输入优惠券名称", trigger: "blur" },
  ],
  coupon_price: [
    { required: true, message: "请输入优惠券面值", trigger: "blur" },
  ],
  user_limit: [{ required: true, message: "使用条件", trigger: "change" }],
  total_count: [{ required: true, message: "输入发放数量", trigger: "blur" }],
  remain_count: [
    { required: true, message: "输入剩余领取数量", trigger: "blur" },
  ],
  receive_limit: [{ required: true, message: "每人限领", trigger: "blur" }],
  receive_type: [
    { required: true, message: "选择领取方式", trigger: "change" },
  ],

  goods_type: [{ required: true, message: "请选择商品类型", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }

  if (type == "add") {
    ruleForm.value = {};
    ruleForm.value.user_limit = 0;
    ruleForm.value.receive_type = 4;
    ruleForm.value.status = 1;
    ruleForm.value.goods_type = 1;
    title.value = "新增";
  } else {
    title.value = "编辑";

    ruleForm.value = Object.assign({}, row);
    getGoods(ruleForm.value.id);
  }

  dialogVisible.value = true;
}
// radio
function changeLimit() {
  ruleForm.value.use_min_price = "";
}
// function changeType(data) {
//   ruleForm.value.reg_start_time = "";
//   ruleForm.value.reg_end_time = "";
//   ruleForm.value.userids = "";
//   if (data == 3) {
//     ruleForm.value.start_time = null;
//     ruleForm.value.end_time = null;
//   }
// }
//
const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.value.user_limit == 1) {
        if (!ruleForm.value.use_min_price) {
          return ElMessage.warning("已选择满减，请输入最低消费金额！");
        }
      }
      // if (ruleForm.value.receive_type == 2) {
      //   if (!ruleForm.value.reg_start_time || !ruleForm.value.reg_end_time) {
      //     return ElMessage.warning("请选择注册时间！");
      //   }
      // } else if (ruleForm.value.receive_type == 3) {
      //   if (!ruleForm.value.userids) {
      //     return ElMessage.warning("请输入指定用户(手机号)！");
      //   }
      // }
      // 领取方式为3 ，不填写领取日期
      // if (ruleForm.value.receive_type !== 3) {
      //   if (!ruleForm.value.start_time || !ruleForm.value.end_time) {
      //     return ElMessage.warning("请选择领取日期！");
      //   }
      // }
      // if (!ruleForm.value.start_use_time || !ruleForm.value.end_use_time) {
      //   return ElMessage.warning("请选择生效日期！");
      // }
      // 指定商品
      if (ruleForm.value.goods_type == 2) {
        if (shopTable.value.length == 0) {
          return ElMessage.warning("请添加商品！");
        }
        let arr = shopTable.value.map((item) => {
          return item.id;
        });
        ruleForm.value.goods_ids = arr.join(",");
      }
      if (!ruleForm.value.id) {
        addApi(ruleForm.value).then((data) => {
          ElMessage.success("新增成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      } else {
        saveApi(ruleForm.value).then((data) => {
          ElMessage.success("编辑成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      }
    }
  });
}
//
let shopPageRef = ref();
function goodsChange(data) {
  ruleForm.value.goods_type = data;
  if (data === 2) {
    if (ruleForm.value.id) {
      getGoods(ruleForm.value.id);
    }
  } else {
    shopTable.value = [];
  }
}
let shopTable = ref([]);
function selectFun(row) {
  if (row.selectData) {
    if (
      !shopTable.value.some((item, i) => {
        return item.code == row.code;
      })
    ) {
      shopTable.value.push(row);
    }
    console.log(shopTable.value);
  } else {
    shopTable.value.forEach((item, i) => {
      if (item.code == row.code) {
        shopTable.value.splice(i, 1);
      }
    });
  }
}
function imgSrc(path) {
  return import.meta.env.VITE_APP_BASE_API + path;
}
function openShop() {
  shopPageRef.value.initFun();
}
function del(i) {
  shopTable.value.splice(i, 1);
}
function getGoods(id) {
  coupon_goodsApi({
    id: id,
  }).then((data) => {
    shopTable.value = data;
  });
}
onMounted(() => {});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.coupon-dialog {
  overflow: hidden;
  :deep(.el-form-item) {
    width: 50%;
    margin-right: 0;
    padding-right: 10px;
    box-sizing: border-box;

    .el-input {
      width: 100%;
    }
  }
  .manage-info {
    display: flex;
    .img-box {
      align-self: center;
    }
    .right {
      margin-left: 10px;
      align-self: center;
      span {
        color: #409eff;
      }
    }
  }
  .select-shop {
  }
  .select-shop-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}
</style>
